package org.indi.yudidi;

// 事务1: 对2条数据进行修改,一增一减,模拟转账操作.
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.*;

public class User1TX {

    private static final Logger LOG = LoggerFactory.getLogger(User1TX.class);

    public static void main(String[] args) throws SQLException {


        String selectSql = "select quantity FROM gooos WHERE id = ?";
        String updateSql = "UPDATE goods SET quantity = ? WHERE id = ?";

        Connection dbConnection = getDBConnection();
        LOG.debug("Begin");
        dbConnection.setAutoCommit(false);

        PreparedStatement plusAmountPS = dbConnection.prepareStatement(selectSql);
        plusAmountPS.setInt(1, 100);
        ResultSet rs = plusAmountPS.executeQuery();

        int quantity = 0;
        while (rs.next()) {
           quantity = rs.getInt(1);
        }

        PreparedStatement minusAmountPS = dbConnection.prepareStatement(updateSql);
        minusAmountPS.setInt(1, quantity-1);
        minusAmountPS.setInt(2, quantity-1);
        minusAmountPS.executeUpdate();

        dbConnection.commit();
        LOG.debug("Done!");

        plusAmountPS.close();
        minusAmountPS.close();
        dbConnection.close();
    }

    private static void simulateError() throws SQLException {
        throw new SQLException("Simulate some error!");
    }

    private static Connection getDBConnection() throws SQLException {
        String DB_DRIVER = "com.mysql.jdbc.Driver";
        String DB_CONNECTION = "jdbc:mysql://localhost:3306/test";
        String DB_USER = "root";
        String DB_PASSWORD = "admin";
        try {
            Class.forName(DB_DRIVER);
        } catch (ClassNotFoundException e) {
            LOG.error(e.getMessage());
        }
        return DriverManager.getConnection(DB_CONNECTION, DB_USER, DB_PASSWORD);
    }
}
